﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using QuanLyThuPhiTaiLieu.Common;
using QuanLyThuPhiTaiLieu.Entity;
using QuanLyThuPhiTaiLieu.Model;
using System.IO;

namespace QuanLyThuPhiTaiLieu.Biz
{
    public class AttachmentBiz : BaseBiz
    {
        public int SaveItem(Attachment item)
        {
            var dbContext = new Context();
   
            dbContext.Attachments.Add(item);
            int newId = dbContext.SaveChanges();

            return newId;
        }

        public void UpdateItem(Attachment item)
        {
            var dbContext = new Context();
            dbContext.Entry(item).State = EntityState.Modified;
            dbContext.SaveChanges();
        }
                
        public Attachment LoadItem(int id)
        {
            var dbContext = new Context();
            return (from item in dbContext.Attachments
                    where item.Id == id
                    select item).First();
        }

        public string SaveAttachmentsToTempFolder(int id)
        {
            Attachment attachment = LoadItem(id);

            if (attachment != null)
            {

                string folderName = Guid.NewGuid().ToString();
                string folderPath = Path.Combine(Path.GetTempPath(), folderName);
                Directory.CreateDirectory(folderPath);

                string filePath = Path.Combine(folderPath, attachment.FileName);
                File.WriteAllBytes(filePath, attachment.Content);

                return filePath;
            }
            return string.Empty;
        }
        
    }
}
